//
//  ViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/16.
//

#import "ViewController.h"
#import "CodeViewController.h"
#import "LognViewController.h"
#import "PhonePickView.h"
#import "PassWordViewController.h"
#import "FaceIDViewController.h"
#import "HomeViewController.h"

@interface ViewController ()<UITextFieldDelegate,pickerDelegate,NoNetworkViewDelegate>
@property(nonatomic,strong)TKLtextFiled * phoneFiled;
@property(nonatomic,strong)TKLtextFiled * passWordFiled;
@property(nonatomic,strong)TKLlable * messageLab;
@property(nonatomic,strong)UIView * messageView;
@property (assign,nonatomic) NSInteger BiometryTypeNumber;
@property (strong,nonatomic) NSString * BiometryTypeStr;
@property(nonatomic,strong)NSMutableArray * phoneArr;
@property(nonatomic,strong)NSString *authorizationCode;
@property(nonatomic,strong)NSString *authorizationKey;
@property(nonatomic,strong)NSString *pushType;
@property(nonatomic,strong)MBProgressHUD *hud;
@property(nonatomic,strong)UIButton * isHiddenBtn;
@property(nonatomic,strong)NSString * userPhone;
@end

static SignMode mode = SignModeRaw;
static IMHashType hashType = IMHashTypeSM3;


@implementation ViewController

-(NSMutableArray *)phoneArr{
    
    if (!_phoneArr) {
        _phoneArr = [NSMutableArray array];
    }
    return _phoneArr;
    
}
-(void)viewWillAppear:(BOOL)animated{
    
  self.navigationController.navigationBarHidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    //注册通知 证书下载成功登录
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cerCallBack:) name:@"downCerSuccess" object:nil];
    
    // Do any additional setup after loading the view.
    [self  loadUIView];
    
    [self faceID];
  
   

}

-(void)cerCallBack:(NSNotification*)sender{

    [self userIsResgitUrlWithPhone];
    
}
- (void)delePassWord:(NSNotification *)notification {
    
   
  
    self.passWordFiled.text =@"";
    
    
}

-(void)loadUIView{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(delePassWord:) name:@"delePassWord" object:nil];
    
    TKLlable * lognLab = [TKLlable labelWithFrame:CGRectMake(30, 100, 50, 30) text:@"登录" textColor:JhColor(51, 51, 51) font:Font_6(24) textAlignment:Textleft backgroundColor:Ccolor];
    
    lognLab.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];

    [self.view addSubview:lognLab];
    
    //提示信息
    self.messageLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+30, kWidth-60, 14) text:@"" textColor:[UIColor redColor] font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];
    self.messageLab.hidden = YES;
    [self.view addSubview:self.messageLab];
    
    
    
    self.phoneFiled = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+50,kWidth-120 , 40) text:@"请输入资金账号" textColor:JhColor(51, 51, 51) font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    self.phoneFiled.keyboardType = UIKeyboardTypeDefault;
    self.phoneFiled.delegate = self;
    [self.view addSubview:self.phoneFiled];
    self.phoneFiled.text = self.userName;
    self.passWordFiled = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(self.phoneFiled.frame)+40, kWidth-120, 40) text:@"请输入资金账号密码" textColor:JhColor(51, 51, 51) font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    [self.view addSubview:self.passWordFiled];
    
    
    
    self.passWordFiled.secureTextEntry= YES;
    //本地的第一个用户
    IMUser * user = [IMUser shareUser];


    //密文切换
    
    self.isHiddenBtn = [UIButton createBtnFrame:CGRectMake(CGRectGetMaxX(self.phoneFiled.frame)+30, CGRectGetMaxY(lognLab.frame)+50, 30, 20) title:@"" bgImageName:@"yincang" action:^(UIButton *button) {
        [self.view endEditing:YES];
        
        [self ishiddenAction];
        
    }];
    
    self.isHiddenBtn.selected = NO;
//    [self.isHiddenBtn setTitleColor:Bcolor forState:UIControlStateNormal];
    [self.view addSubview:self.isHiddenBtn];
    
    
    
    
    self.messageView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.phoneFiled.frame), kWidth-60, 1)];
    self.messageView.backgroundColor = JhColor(153, 153, 153);
    [self.view addSubview:self.messageView];
    
    
    UIView * linView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.passWordFiled.frame), kWidth-60, 1)];
    linView.backgroundColor = JhColor(153, 153, 153);
    [self.view addSubview:linView];
    
    //next
    UIButton * nextBtn = [UIButton createBtnFrame:CGRectMake(30, CGRectGetMaxY(linView.frame)+20, kWidth-60, 44) title:@"下一步" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
        self.pushType = @"0";
        self.phoneFiled.text = [self.phoneFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        self.passWordFiled.text =[self.passWordFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (self.phoneFiled.text.length > 0) {
            
            if (self.passWordFiled.text.length > 0) {
                //查询是否激活
                
                [self userIsResgitUrlWithPhone];
            }else{
                [MBProgressHUD showError:@"请输入资金账号密码" toView:self.view];
            }
           
            
        
        }else{
            [MBProgressHUD showError:@"请输入资金账号" toView:self.view];
        
        }
        

        
    }];
//    nextBtn
    nextBtn.backgroundColor = JhColor(21, 126, 251);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = 5;
    [self.view addSubview:nextBtn];
    
    UIButton * forgetWordBtn = [UIButton createBtnFrame:CGRectMake(kWidth-100, CGRectGetMaxY(nextBtn.frame)+10, 80, 18) title:@"忘记密码？" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
      
        self.phoneFiled.text = [self.phoneFiled.text stringByReplacingOccurrencesOfString:@" " withString:@""];
     
        if (self.phoneFiled.text.length > 0) {
            //如果是忘记密码1
            self.pushType = @"1";

            //查询是否激活
            
            [self userIsResgitUrlWithPhone];
            
          
        }else{
            
            [MBProgressHUD showError:@"请先输入资金账号" toView:self.view];
            
        }
        
        
       
        
        
    }];
    [forgetWordBtn setTitleColor:JhColor(21, 126, 251) forState:UIControlStateNormal];
    [self.view addSubview:forgetWordBtn];
    
    
    

}

-(void)userIsResgitUrlWithPhone{
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = NSLocalizedString(@"请稍等", @"HUD loading title");
    
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kVerUserNumber_Activity_Api WithString:self.phoneFiled.text WithReturnValeuBlock:^(id  _Nonnull returnValue) {
          NSLog(@"%@",returnValue)  ;
        
        if ([returnValue[@"code"] intValue] == 200) {
            ;
            NSDictionary * mindic = returnValue[@"data"];
            self.userPhone = mindic[@"mobile"];
            if ([mindic[@"isMobile"] intValue] == 3) {
                //为3  激活  判断是否有证书
                NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
                //本机是否开启生物登录
                NSArray * deviceArr = mindic[@"muDevices"];
                if ([deviceArr isKindOfClass:[NSNull class]] || [deviceArr isEqual:[NSNull null]]) {
                  
                    //为开启
                    [stand setObject:@"0" forKey:@"bio"];
                }else{
                    [deviceArr enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                            if ([obj[@"deviceId"] isEqualToString:[IMSecurity getDeviceIdentifier]]&& [obj[@"fpSwitch"]intValue]==1) {
                              
                                [stand setObject:@"1" forKey:@"bio"];
                            }else{
                                [stand setObject:@"0" forKey:@"bio"];
                            }
                        }];
                  
                    
                    
                    
                }
                
                
                if (self.userPhone.length == 11) {
                    [self hasCerWithUserName];;
                }else{
                    [MBProgressHUD showMessage:[NSString stringWithFormat:@"账户关联手机号:%@错误",self.userPhone] toView:self.view];
                }
                
                
             
                
                
                
            }else{
                self.hud.hidden = YES;
                self.messageLab.text = @"资金账号未激活,请输入正确的资金账号";
                self.messageLab.hidden = NO;
                self.messageView.backgroundColor = JhColor(239, 45, 47);
            }
            
            
            
            
        }else if([returnValue[@"code"] intValue] == 999){
            self.hud.hidden = YES;
//            NSLog(@"%@",returnValue[@"msg"]);
            self.messageLab.text = @"请输入正确的资金账号";
            self.messageLab.hidden = NO;
            self.messageView.backgroundColor = JhColor(239, 45, 47);
        }
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            ;
        } WithFailureBlock:^{
            ;
        }];
    
    
    

    
 
    
}

-(void)userLoginUrl{
    

    
    NSString * name = [NSString stringWithFormat:@"%@@@%@",self.phoneFiled.text,self.passWordFiled.text];

    NSString * firstsatr = [TKLTools encryptPassword:name key:self.authorizationCode];
 
 
    NSString * password = [NSString stringWithFormat:@"%@@@%@",firstsatr,self.authorizationKey];

  
        
        FMDatabase *database =  [DataBaseTool openDataBase];
        
        NSString *selectSql = [NSString stringWithFormat:@"select * from userCer where userName =  '%@'",self.phoneFiled.text];

        FMResultSet *resultSet = [database executeQuery:selectSql];
        while ([resultSet next]) {

     
            
            NSString *payPassord  = [resultSet stringForColumn:@"payWord"];

            IMUser * user = [IMUser userWithUserName:self.phoneFiled.text];

            [user.cert signWithPIN:payPassord Plain:[NSString stringWithFormat:@"%@+%@",self.phoneFiled.text,[user.cert getCertInfoWithItem:CertItemTypeDN]] encoding:NSUTF8StringEncoding hashType:IMHashTypeSM3 mode:mode andCompleteBlock:^(int resultCode, NSString *signResult) {
                {
//                    NSLog(@"%@",resultCode);
                    if (resultCode == IM_ER_SUCCESS) {
                        NSLog(@"%@",signResult);
                        if (signResult != nil) {
            
                            NSDictionary * dic =@{@"grantType":@"password",@"password":password,@"username":self.phoneFiled.text,@"certDn":[user.cert getCertInfoWithItem:CertItemTypeDN],@"sign":signResult};
                            [self loginWithDic:dic];
                            
                        }
                    }else{
                        [MBProgressHUD showError:@"签名失败" toView:self.view];
                    }
                }
            }];
            
        }
        [database close];
    




}


-(void)loginWithDic:(NSDictionary *)dic{
//    NSLog(@"%@",dic);
   
    [AFNetworkUtils POST_Raw:kUser_Login_Api body:dic.yy_modelToJSONString head:nil success:^(NSDictionary * _Nonnull responseObject) {
//        NSLog(@"密码结果%@",responseObject);
        if ([responseObject[@"code"] intValue] ==200) {
           
            self.hud.hidden = YES;
            NSDictionary * dataDic= responseObject[@"data"];
             NSString * dataStr = dataDic[@"accessToken"];
            
            
            NSString *dealString =dataDic[@"tokenType"];
                NSString *resultString = [TKLTools strFirstBig:dealString];
              
            dataStr = [NSString stringWithFormat:@"%@ %@",resultString,dataStr];
             NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
             [stand setObject:dataStr forKey:@"token"];
             NSDictionary * dic = [TKLTools jwtDecodeWithJwtString:dataStr];
      
             NSString * jsonStr = dic[@"user_name"];
             NSDictionary * jsonDic = [TKLTools dictionaryWithJsonString:jsonStr];
             NSString * isChangePass = jsonDic[@"firstEnter"];
//            NSLog(@"%@",jsonDic);
            [stand setObject:self.phoneFiled.text forKey:@"userName"];
            
            //插入数据库
            [self insterDataList];

             //是否修改过密码  1和 2  均未修改

             if ([isChangePass intValue] == 1 || [isChangePass intValue] ==2) {
                 PassWordViewController * passVC = [[PassWordViewController alloc]init];
     
                 passVC.modalPresentationStyle = 0;
                 passVC.pushPath = @"newUser";
                 passVC.verifyCode = @"";
                 [self presentViewController:passVC animated:YES completion:nil];

             }else{
                 //判断设备是否开启了
            //开启就跳首页   没开启就跳到设置
                 
                 NSUserDefaults * stand = [NSUserDefaults standardUserDefaults];
                 
                 if ([[stand objectForKey:@"bio"] isEqualToString:@"1"]) {
                     HomeViewController * homeVC = [[HomeViewController alloc]init];
                     homeVC.modalPresentationStyle = 0;
                     [self presentViewController:homeVC animated:YES completion:nil];
                 }else{
                     
                     if (self.BiometryTypeNumber == 0) {
                         HomeViewController * homeVC = [[HomeViewController alloc]init];
                         homeVC.modalPresentationStyle = 0;
                         [self presentViewController:homeVC animated:YES completion:nil];
                     }else{
                         FaceIDViewController * faceVC = [[FaceIDViewController alloc]init];
                         faceVC.pushPath = @"login";
                           faceVC.modalPresentationStyle = 0;
                           faceVC.userName = self.phoneFiled.text;
                           faceVC.BiometryTypeStr = self.BiometryTypeStr;
                           faceVC.BiometryTypeNumber = self.BiometryTypeNumber;
                         [self presentViewController:faceVC animated:YES completion:nil];
                     }
                     
                   
                 }
                 
             }

        }else{
            self.hud.hidden = YES;
           
                [MBProgressHUD showError:responseObject[@"msg"] toView:self.view];
          
        }

        } failure:^(NSString * _Nonnull error) {
            self.hud.hidden =YES;
        }];
}



-(void)hasCerWithUserName{
    
    IMUser *user = [IMUser userWithUserName:self.phoneFiled.text];
    self.hud.hidden = YES;
    if (user == nil) {

        CodeViewController * codeVC =[[CodeViewController alloc]init];
        codeVC.userName  = self.phoneFiled.text;
        if ([self.pushType isEqualToString:@"1"]) {
            codeVC.pushPath = @"cerForget";
        }else{
            codeVC.pushPath = @"cer";
        }
       
        codeVC.phoneNumberStr = self.userPhone;
        codeVC.modalPresentationStyle = 0;
        [self presentViewController:codeVC animated:YES completion:nil];
        
    }else{
        
        if (![IMCert hasCertWithUsername:user.username]) {
            CodeViewController * codeVC =[[CodeViewController alloc]init];
            codeVC.userName  = self.phoneFiled.text;
            if ([self.pushType isEqualToString:@"1"]) {
                codeVC.pushPath = @"cerForget";
            }else{
                codeVC.pushPath = @"cer";
            }
            codeVC.phoneNumberStr = self.userPhone;
            codeVC.modalPresentationStyle = 0;
            [self presentViewController:codeVC animated:YES completion:nil];
            
        }else{
            
            
           [ user.cert getCertStateWithCompleteBlock:^(int resultCode, NSDictionary *dictState) {

                if (resultCode == IM_ER_SUCCESS) {

                  //证书状态
                    if ([dictState[@"isexpired"] intValue] == 0) {
                        //不过期
                        //判断是不是点击忘记密码
                        if ([self.pushType isEqualToString:@"1"]) {
                            
                            CodeViewController * codeVC = [[CodeViewController alloc]init];
                            codeVC.userName  = self.phoneFiled.text;
                            codeVC.pushPath = @"newForget";
                            codeVC.phoneNumberStr = self.userPhone;
                            codeVC.modalPresentationStyle = 0;
                            [self presentViewController:codeVC animated:YES completion:nil];
                            
                            
                        }else{
                            //有证书获取加密盐
                            [self getKey];
                        }
                        
                       
  
                    }else{
                        //过期
                        [user.cert deleteCert ];
                        CodeViewController * codeVC =[[CodeViewController alloc]init];
                        codeVC.phoneNumberStr = self.userPhone;
                        codeVC.pushPath = @"cer";
                        codeVC.userName  = self.phoneFiled.text;

                        codeVC.modalPresentationStyle = 0;
                        [self presentViewController:codeVC animated:YES completion:nil];
                    }
                    
                    
                
                }else{
                    [user.cert deleteCert];
                    CodeViewController * codeVC =[[CodeViewController alloc]init];
                    codeVC.phoneNumberStr = self.userPhone;
                    codeVC.pushPath = @"cer";
                    codeVC.userName  = self.phoneFiled.text;

                    codeVC.modalPresentationStyle = 0;
                    [self presentViewController:codeVC animated:YES completion:nil];
                  
//                    NSLog(@"获取证书状态失败:%d,%@",resultCode,dictState);
                }
            }];
        }
        
        
    }
    

}

-(void)getKey{
    

    
    [AFNetworkUtils GET:kAuthorizationCode_Api body:nil head:nil success:^(NSDictionary * _Nonnull responseObject) {
           NSLog(@"%@",responseObject);
        if ([responseObject[@"code"]intValue] == 200) {
            self.authorizationCode = responseObject[@"data"][@"authorizationValue"];
            self.authorizationKey = responseObject[@"data"][@"authorizationKey"];
            
            
            [self userLoginUrl];
            
        }else{
            self.hud.hidden = YES;
            [MBProgressHUD showError:responseObject[@"msg"] toView:self.view];
        }

        } failure:^(NSString * _Nonnull error) {
            self.hud.hidden =YES;
            NSLog(@"%@",error);
        }];
}


-(void)loadPickView{
    PhonePickView *pView = [[PhonePickView alloc ] initWithFrame:CGRectMake(0, kHeight-200, kWidth, 200) arr:self.phoneArr ];
    pView.delegate = self;

    
}
-(void)selectIndex:(NSInteger)index { //根据索引取出传入数组的值
//NSLog(@"%ld",(long)index);
    self.phoneFiled.text = self.phoneArr[index];
}
-(void)ishiddenAction{
    
    
    if (self.isHiddenBtn.selected == NO) {
        self.isHiddenBtn.selected = YES;
        [self.isHiddenBtn setBackgroundImage:[UIImage imageNamed:@"xianshi"] forState:UIControlStateNormal];
    }else{
        self.isHiddenBtn.selected = NO;
        [self.isHiddenBtn setBackgroundImage:[UIImage imageNamed:@"yincang"] forState:UIControlStateNormal];
    }
    // 取反

    self.passWordFiled.secureTextEntry = !self.passWordFiled.secureTextEntry;
 
// 获得输入的值

    NSString *content = self.passWordFiled.text;
  
 // 解决输入框从密文切换明文时出现空格的问题

    self.passWordFiled.text = @"";


    self.passWordFiled.text = content;

 //如果是密文转明文进行二次编辑不会出现清空现象,如果是明文转密文进行二次编辑就会出现清空现象,进行判断,如果切换后此时输入框是密文状态,就保存原有内容并赋值给输入框,这样就不会出现清空现象了

   if (self.passWordFiled.secureTextEntry) {

 // 解决输入框从明文切换为密文时进行二次编辑出现清空现象

       [self.passWordFiled insertText:content];
    

 }

    
}

    
    
-(void)faceID{
    
    self.BiometryTypeNumber = [BiomerTool isSupportBiometrics ];
   
    if (self.BiometryTypeNumber == 1) {
        self.BiometryTypeStr = @"指纹";
    }else if (self.BiometryTypeNumber == 2){
        self.BiometryTypeStr = @"面部";
    }else{
        self.BiometryTypeStr = @"生物";
    }
    
}

//插入本地数据库
-(void)insterDataList{
    
   
    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from user where userName = '%@'",self.phoneFiled.text];
    
    FMResultSet *resultSet = [database executeQuery:selectSql];
   
    
    if ( [resultSet next]) {
        ;
    }else{
        NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO 'user' ('userName', 'passWord') VALUES ('%@', '%@')",self.phoneFiled.text,self.passWordFiled.text];
               BOOL result = [database executeUpdate:insertSql];
      if (!result) {
          NSLog(@"插入失败");
      }else{
          NSLog(@"插入成功");
      }
        
    }
    
    [database close];
}
-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    
    self.messageLab.hidden = YES;
    self.messageView.backgroundColor = JhColor(153, 153, 153);
    
}

@end
